package com.google.code.sfa.parse;

import org.biojava.bio.symbol.Symbol;
import org.biojava.bio.symbol.SymbolList;
import org.biojava.bio.seq.DNATools;
import java.util.Iterator;

public class IntegerNMerParser {
    private Symbol _a, _t, _c, _g; //0,1,2,3
    private int _size;
    private int _mask;
    private int _current;
    private Iterator _iter;
    private boolean _new;

    public IntegerNMerParser( int size) {

	_a = DNATools.a();
	_t = DNATools.t();
	_c = DNATools.c();
	_g = DNATools.g();
	
	_size = size;
	_mask = ~ ( 0xFFFFFFFF << (_size*2) );
    } 

    public void reset( SymbolList sequence) {
	_new = true;
	_current = 0;
	_iter = sequence.iterator();
    }


    public boolean advance() {
	int loaded;
	if( _new) {
	    loaded = 0;
	} else {
	    loaded = _size - 1;
	}
	while( loaded < _size) {
	    if( !_iter.hasNext() ) {
		return false;
	    }
	    _current = _current << 2;
	    _current &= _mask;
	    loaded++;
	    Symbol s = (Symbol) _iter.next();
	    if( s == _a) {
		_current |= 0;
	    } else if( s == _t) {
		_current |= 1;
	    } else if( s == _c) {
		_current |= 2;
	    } else if( s == _g) {
		_current |= 3;
	    } else {
		// reset here because there was an ambiguous symbol
		_current = 0;
		loaded = 0;
	    }

	}
	_new = false;
	return true;	    
    }

    public int current() {
	return _current;
    }

}